import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

///
///* future：FutureBuilder依赖的Future，通常是一个异步耗时任务。
///   initialData：初始数据，用户设置默认数据。
///   builder：Widget构建器；该构建器会在Future执行的不同阶段被多次调用，构建器签名如下：
///*
/// */
class FutureBuilderWidget extends StatefulWidget {
  final String? text;

  FutureBuilderWidget({this.text}) : super();

  @override
  State<StatefulWidget> createState() {
    return _FutureBuilderState(text??"");
  }
}

class _FutureBuilderState extends State {
  String ?title;

  _FutureBuilderState(String text) {
    title = text;
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
        title: Text(
          title??"",
          style: TextStyle(fontSize: 18),
        ),
      ),
      body: Center(
        child: FutureBuilder<String>(
          future: mockNetworkData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            // 请求已结束 【ConnectionState.active只在StreamBuilder中才会出现】
            if (snapshot.connectionState == ConnectionState.done) {
              if (snapshot.hasError) {
                // 请求失败，显示错误
                return Text("Error: ${snapshot.error}");
              } else {
                // 请求成功，显示数据
                return Text("Contents: ${snapshot.data}");
              }
            } else {
              // 请求未结束，显示loading
              return CircularProgressIndicator();
            }
          },
        ),
      ),
    );
  }
}

Future<String> mockNetworkData() async {
  return Future.delayed(Duration(seconds: 2), () async {
    return "我是从互联网上获取的数据";
  });
}
